<template>
  <div class="menu">
   <div class="row">
        <div class="col-md-6">
                <div class="form-group">
                    <label for="connect">WebSocket connection:</label>
                    <button id="connect" class="btn btn-default" @click="connect" :disabled="websocket">Connect</button>
                    <button id="disconnect" class="btn btn-default" @click="close" :disabled="!websocket">Disconnect
                    </button>
                </div>
        </div>
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="name">What is your name?</label>
                    <input type="text" id="name" v-model="message" class="form-control">
                </div>
                <button id="send" class="btn btn-default" @click="sendMsg" :disabled="!websocket">Send</button>
            </form>
        </div>
    </div>
    <div class="row">
        <div v-for="(item,index) in returnMsg" :key="item">
            {{item}}
        </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      message: "hello",
      websocket: null,
      returnMsg: []
    };
  },
  methods: {
    connect() {
      this.websocket = new WebSocket("ws://localhost:8080/websocket");
      this.websocket.onmessage = event => {
        this.returnMsg.push(event.data);
      };
    },
    sendMsg() {
      this.websocket.send(this.message);
    },
    close() {
      this.websocket.close();
      this.websocket=null;
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.menu {
  width: 40%;
}
</style>
